<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Shop;
use App\Models\User;
use App\Models\Seller;
use App\Models\BusinessSetting;
use Auth;
use Hash;
use App\Notifications\EmailVerificationNotification;

class ShopController extends Controller
{

    public function __construct()
    {
        $this->middleware('user', ['only' => ['index']]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $shop = Auth::user()->shop;
        return view('frontend.user.seller.shop', compact('shop'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        if (Auth::check() && Auth::user()->user_type == 'admin') {
            flash(translate('Admin can not be a seller'))->error();
            return back();
        } else {
            return view('frontend.seller_form');
        }
    }

    public function seller_apply()
    {
        if (Auth::check() && Auth::user()->user_type == 'admin') {
            flash(translate('Admin can not be a seller'))->error();
            return back();
        } else {
            return view('frontend.seller_apply');
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */

    function doupload($file = 'file')
    {
        $dir = $_SERVER['DOCUMENT_ROOT'] . '/images/';
        $allowedExts = array("gif", "jpeg", "jpg", "png");
        $temp = explode(".", $_FILES[$file]["name"]);

        $extension = end($temp);     // 获取文件后缀名
        if ((($_FILES[$file]["type"] == "image/gif")
                || ($_FILES[$file]["type"] == "image/jpeg")
                || ($_FILES[$file]["type"] == "image/jpg")
                || ($_FILES[$file]["type"] == "image/pjpeg")
                || ($_FILES[$file]["type"] == "image/x-png")
                || ($_FILES[$file]["type"] == "image/png"))
            && ($_FILES[$file]["size"] < 2040000800)   // 小于 200 kb
            && in_array($extension, $allowedExts)) {
            if ($_FILES[$file]["error"] > 0) {
                # echo "错误：: " . $_FILES["file"]["error"] . "<br>";
            } else {
                #echo "上传文件名: " . $_FILES["file"]["name"] . "<br>";
                #echo "文件类型: " . $_FILES["file"]["type"] . "<br>";
                #echo "文件大小: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
                #echo "文件临时存储的位置: " . $_FILES["file"]["tmp_name"] . "<br>";

                // 判断当前目录下的 upload 目录是否存在该文件
                // 如果没有 upload 目录，你需要创建它，upload 目录权限为 777

                // 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
                $name = md5(microtime() . mt_rand(1000, 9999)) . '.' . $extension;

                copy($_FILES[$file]["tmp_name"], $dir . $name);

            }
        }
        return $name;
    }


    public function store(Request $request)
    {
        set_time_limit(0);
        ini_set("upload_max_filesize", "525M");
        ini_set("max_execution_time", 600); //--- 10 minutes
        ini_set("post_max_size", "235M");
        ini_set("file_uploads", "On");

        $user = null;
        if (!Auth::check()) {
            if (User::where('email', $request->email)->first() != null) {
                flash(translate('Email already exists!'))->error();
                return back();
            }
            if ($request->password == $request->password_confirmation) {
                $user = new User;
                $user->name = $request->name;
                $user->email = $request->email;
                $user->user_type = "seller";
                $user->password = Hash::make($request->password);
                $user->save();
            } else {
                flash(translate('Sorry! Password did not match.'))->error();
                return back();
            }
        } else {
            $user = Auth::user();
            if ($user->customer != null) {
                $user->customer->delete();
            }
            $user->user_type = "seller";
            $user->save();
        }

        $seller = new Seller;
        $seller->user_id = $user->id;

        if (isset($_FILES['reg_idcard']) && $_FILES['reg_idcard']['tmp_name']) {
            $seller->reg_idcard = $this->doupload('reg_idcard');
        }
        if (isset($_FILES['reg_hand_idcard']) && $_FILES['reg_hand_idcard']['tmp_name']) {
            $seller->reg_hand_idcard = $this->doupload('reg_hand_idcard');
        }
        if (isset($_FILES['reg_yyzz']) && $_FILES['reg_yyzz']['tmp_name']) {
            $seller->reg_yyzz = $this->doupload('reg_yyzz');
        }
        if (isset($request->reg_jjlxr)) {
            $seller->reg_jjlxr = $request->reg_jjlxr;
        }
        if (isset($request->reg_email)) {
            $seller->reg_email = $request->reg_email;
        }
        $seller->save();


        if (addon_is_activated('affiliate_system')) {
            //$allow_customer_join_affiliate_user = \App\Models\AffiliateOption::where('type', 'allow_customer_join_affiliate_user')->first()->status ?? 0;
            $affiliate_user = \App\Models\AffiliateUser::where('user_id', $user->id)->first();
            if (!$affiliate_user) $affiliate_user = new \App\Models\AffiliateUser;
            $affiliate_user->user_id = $user->id;
            //$affiliate_user->informations = null;
            $affiliate_user->status = 1;
            $affiliate_user->save();
        }

        if (Shop::where('user_id', $user->id)->first() == null) {
            $shop = new Shop;
            $shop->user_id = $user->id;
            $shop->name = $request->name;
            $shop->address = $request->address;
            $shop->slug = preg_replace('/\s+/', '-', $request->name);

            if ($shop->save()) {
                auth()->login($user, false);
                if (BusinessSetting::where('type', 'email_verification')->first()->value != 1) {
                    $user->email_verified_at = date('Y-m-d H:m:s');
                    $user->save();
                } else {
                    $user->notify(new EmailVerificationNotification());
                }

                flash(translate('Your Shop has been created successfully!'))->success();
                return redirect()->route('shops.index');
            } else {
                $seller->delete();
                $user->user_type == 'customer';
                $user->save();
            }
        }

        flash(translate('Sorry! Something went wrong.'))->error();
        return back();
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $shop = Shop::find($id);

        if ($request->has('name') && $request->has('address')) {
            if ($request->has('shipping_cost')) {
                $shop->shipping_cost = $request->shipping_cost;
            }

            $shop->name = $request->name;
            $shop->address = $request->address;
            $shop->phone = $request->phone;
            $shop->slug = preg_replace('/\s+/', '-', $request->name) . '-' . $shop->id;
            $shop->meta_title = $request->meta_title;
            $shop->meta_description = $request->meta_description;
            $shop->logo = $request->logo;
        }

        if (
            $request->has('delivery_pickup_longitude') &&
            $request->has('delivery_pickup_latitude')
        ) {

            $shop->delivery_pickup_longitude = $request->delivery_pickup_longitude;
            $shop->delivery_pickup_latitude = $request->delivery_pickup_latitude;
        } elseif (
            $request->has('facebook') ||
            $request->has('google') ||
            $request->has('twitter') ||
            $request->has('youtube') ||
            $request->has('instagram')
        ) {
            $shop->facebook = $request->facebook;
            $shop->instagram = $request->instagram;
            $shop->google = $request->google;
            $shop->twitter = $request->twitter;
            $shop->youtube = $request->youtube;
        } else {
            $shop->sliders = $request->sliders;
        }

        if ($shop->save()) {
            flash(translate('Your Shop has been updated successfully!'))->success();
            return back();
        }

        flash(translate('Sorry! Something went wrong.'))->error();
        return back();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function verify_form(Request $request)
    {
        if (Auth::user()->seller->verification_info == null) {
            $shop = Auth::user()->shop;
            return view('frontend.user.seller.verify_form', compact('shop'));
        } else {
            flash(translate('Sorry! You have sent verification request already.'))->error();
            return back();
        }
    }

    public function verify_form_store(Request $request)
    {
        $data = array();
        $i = 0;
        foreach (json_decode(BusinessSetting::where('type', 'verification_form')->first()->value) as $key => $element) {
            $item = array();
            if ($element->type == 'text') {
                $item['type'] = 'text';
                $item['label'] = $element->label;
                $item['value'] = $request['element_' . $i];
            } elseif ($element->type == 'select' || $element->type == 'radio') {
                $item['type'] = 'select';
                $item['label'] = $element->label;
                $item['value'] = $request['element_' . $i];
            } elseif ($element->type == 'multi_select') {
                $item['type'] = 'multi_select';
                $item['label'] = $element->label;
                $item['value'] = json_encode($request['element_' . $i]);
            } elseif ($element->type == 'file') {
                $item['type'] = 'file';
                $item['label'] = $element->label;
                $item['value'] = $request['element_' . $i]->store('uploads/verification_form');
            }
            array_push($data, $item);
            $i++;
        }
        $seller = Auth::user()->seller;
        $seller->verification_info = json_encode($data);
        if ($seller->save()) {
            flash(translate('Your shop verification request has been submitted successfully!'))->success();
            return redirect()->route('dashboard');
        }

        flash(translate('Sorry! Something went wrong.'))->error();
        return back();
    }
}
